//
//  KKHttpServices.m
//  BurNing
//
//  Created by LIKUN on 15/8/13.
//  Copyright (c) 2015年 LIKUN. All rights reserved.
//

#import "KKHttpServices.h"
#import "DDErrorCodeMapping.h"

static KKHttpServices *httpServices = nil;

@implementation KKHttpServices
+ (instancetype)shareInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        httpServices = [[KKHttpServices alloc]init];
    });
    return httpServices;
}

#pragma mark ---
#pragma mark ---解析Json数据
+ (KKHttpParse *)parseResponse:(id)responseObject
{
    NSMutableDictionary* jsonDic = nil;
    if (responseObject) {
        jsonDic = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
    }else
        return nil;
    
    KKHttpParse *parse = [[KKHttpParse alloc]init];
    parse.responseCode =[DDErrorCodeMapping errorCodeMappingWithServerCode:jsonDic[@"retCode"]];
    parse.responseMsg = jsonDic[@"retMsg"];
    parse.responseJsonOB = jsonDic;
    return parse;
}
#pragma mark ---
#pragma mark ---POST网络请求
+ (void)httpPostUrl:(NSString *)url prams:(NSDictionary *)dic success:(KKSuccessBlock)succsssBlock failure:(KKFailureBlock)failureBlock
             cancel:(KKCancelBlock)cancelBlock{
    [ToolKit checkNetwork];
    if (AFNetworkNotReachability) {
        KKHttpParse* a = [[KKHttpParse alloc] init];
        a.responseCode = DingDongErrorCodeNoNet;
        a.responseMsg = MESSAGE_NoNetwork;
        failureBlock(a);
    }
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:nil error:nil];
    
    [request addValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
    
    NSData *body = nil;
    if (dic) {
        body = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
    }
    [request setHTTPBody:body];
    
    //发起请求
    
    NSURLSessionDataTask *task = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        
        if (!error) {
            NSString *result  =[[ NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            NSLog(@"Reply JSON: %@", result);
            KKHttpParse *parse = [[self class]parseResponse:responseObject];
            if (parse) {
                if (parse.responseCode == DingDongErrorCodeSuccess) {
                    succsssBlock(parse.responseJsonOB,parse);
                }else{
                    //逻辑错误
                    [[self class]setFilter:parse];
                    failureBlock(parse);
                }
            }
        } else {
            NSLog(@"Error: %@, %@, %@", error, response, responseObject);
            KKHttpParse *parse = [[self class]setErrorFilter];
            failureBlock(parse);
        }
        
    }] ;
    
    [task resume];
    cancelBlock(task);
}
+ (void)httpPostUrl:(NSString *)url sign:(NSString *)sign prams:(NSDictionary *)dic success:(KKSuccessBlock)succsssBlock failure:(KKFailureBlock)failureBlock
             cancel:(KKCancelBlock)cancelBlock{
    [ToolKit checkNetwork];
    if (AFNetworkNotReachability) {
        KKHttpParse* a = [[KKHttpParse alloc] init];
        a.responseCode = DingDongErrorCodeNoNet;
        a.responseMsg = MESSAGE_NoNetwork;
        failureBlock(a);
    }
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager.requestSerializer setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
    
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:dic error:nil];
    
    [request addValue:AccessToken forHTTPHeaderField:@"accessToken"];
    [request addValue:sign forHTTPHeaderField:@"sign"];
    [request addValue:AppVersion forHTTPHeaderField:@"version"];
    [request addValue:NowTimeStamp forHTTPHeaderField:@"timestamp"];
    [request addValue:AppType forHTTPHeaderField:@"appType"];
    
    if (dic) {
        NSData *body = [NSJSONSerialization dataWithJSONObject:dic options:kNilOptions error:nil];
        [request setHTTPBody:body];
    }

    
    NSURLSessionDataTask *task = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        
        if (!error) {
            NSString *result  =[[ NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            NSLog(@"Reply JSON: %@", result);
            KKHttpParse *parse = [[self class]parseResponse:responseObject];
            if (parse) {
                if (parse.responseCode == DingDongErrorCodeSuccess) {
                    succsssBlock(parse.responseJsonOB,parse);
                }else{
                    //逻辑错误
                    [[self class]setFilter:parse];
                    failureBlock(parse);
                }
            }
        } else {
            NSLog(@"Error: %@, %@, %@", error, response, responseObject);
            KKHttpParse *parse = [[self class]setErrorFilter];
            failureBlock(parse);
        }

    }];
    [task resume];
    cancelBlock(task);
}
#pragma mark ---
#pragma mark ---逻辑错误msg
+ (void)setFilter:(KKHttpParse *)parse
{
    NSString *msg = parse.responseMsg;
    [parse.responseHead setValue:msg forKey:@"message"];
}
#pragma mark ---
#pragma mark ---网络错误
+ (KKHttpParse *)setErrorFilter
{
    KKHttpParse *a = [[KKHttpParse alloc] init];
    a.responseCode = DingDongErrorCodeNoNet;
    a.responseMsg = MESSAGE_NoNetwork;
    [a.responseHead setValue:MESSAGE_NoNetwork forKey:@"message"];
    return a;
}
#pragma mark 创建建网络错误
+(NSString *) creatHttpErr:(KKHttpParse*) param err:(NSError**)err
{
    if (err != NULL)
    {
        *err = [[NSError alloc] initWithDomain:@"" code:param.responseCode  userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[param.responseHead objectForKey:@"message"],@"msg", nil]];
    }
    return nil;
}


#pragma mark ---
#pragma mark ---文件上传
+ (void)postUploadFile:(NSString *)url sign:(NSString *)sign prams:(NSDictionary *)prams thumbnail:(NSData *)tdata thumname:(NSString *)thumname success:(KKSuccessBlock)succsssBlock failure:(KKFailureBlock)failureBlock
                cancel:(KKCancelBlock)cancelBlock
{
    [ToolKit checkNetwork];
    if (AFNetworkNotReachability) {
        KKHttpParse* a = [[KKHttpParse alloc] init];
        a.responseCode = DingDongErrorCodeNoNet;
        a.responseMsg = MESSAGE_NoNetwork;
        failureBlock(a);
    }
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager.requestSerializer setValue:@"application/octet-stream" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:AccessToken forHTTPHeaderField:@"accessToken"];
    [manager.requestSerializer setValue:sign forHTTPHeaderField:@"sign"];
    [manager.requestSerializer setValue:AppVersion forHTTPHeaderField:@"version"];
    [manager.requestSerializer setValue:NowTimeStamp forHTTPHeaderField:@"timestamp"];
    [manager.requestSerializer setValue:AppType forHTTPHeaderField:@"appType"];

    
    [manager POST:url parameters:prams constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:tdata name:@"file" fileName:thumname mimeType:@"image/png"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
//        NSLog(@"上传文件的进度%@",uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *result  =[[ NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"上传文件的返回%@",result);
        KKHttpParse *parse = [KKHttpServices parseResponse:responseObject];
        if (parse) {
            if (parse.responseCode == DingDongErrorCodeSuccess) {
                succsssBlock(task,parse);
            }else{
                //逻辑错误
                [[self class]setFilter:parse];
                failureBlock(parse);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"上传文件失败的返回%@",error);
        KKHttpParse *parse = [[self class]setErrorFilter];
        failureBlock(parse);
    }];
}
@end
